﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Advisor_ManageCourse : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (Session["isAdmin"] == null)
            {
                Page.Response.Redirect("Default.aspx");
            }
            else if (!(Boolean)Session["isAdmin"])
            {
                DeleteButton.Enabled = false;
            }
            Dictionary<String, String> courses = SharedFunctions.getDptAcronymToString();
            SubjectList.Items.Clear();
            SubjectList.Items.Add(new ListItem("All Courses"));
            foreach (String s in courses.Keys)
            {
                SubjectList.Items.Add(new ListItem(courses[s], s));
            }
            String cid = Request.QueryString["cid"];
            if (cid != null) ManageGivenCourse(cid);
        }
    }
    protected void HomeButton_Click(object sender, EventArgs e)
    {
        Response.Redirect("~/Advisor/Default.aspx");
    }
    protected void HelpButton_Click(object sender, EventArgs e)
    {
        Response.Redirect("~/Advisor/Help.aspx");
    }
    protected void SaveCourseButton_Click(object sender, EventArgs e)
    {
        removeAllCourseAttributes();
        addAllCourseAttributes();
        MessageBox.Show("Course updated");
        CancelButton_Click(sender, e);
    }

    private void addAllCourseAttributes()
    {
        //add prereqs
        foreach (ListItem i in PrereqList.Items)
        {
            if (StoredProcedures.addPrereq(i.Value, CourseID.Text) == 0)
            {
                //error condition
            }
        }
        //add coreqs
        foreach (ListItem i in CoreqList.Items)
        {
            if (StoredProcedures.addCoreq(i.Value, CourseID.Text) == 0)
            {
                //error condition
            }
        }
        foreach (ListItem i in TagList.Items)
        {
            if (StoredProcedures.addTag(CourseID.Text, i.Value) == 0)
            {
                //error condition
            }
        }
        //add tags
    }
    private void removeAllCourseAttributes()
    {
        if (StoredProcedures.removeAllPrereqs(CourseID.Text) == 0)
        {
            //error condition
        }
        if (StoredProcedures.removeAllCoreqs(CourseID.Text) == 0)
        {
            //error condition
        }
        if (StoredProcedures.removeAllTags(CourseID.Text) == 0)
        {
            //error condition
        }
    }
    protected void CancelButton_Click(object sender, EventArgs e)
    {
        PrereqList.Items.Clear();
        CoreqList.Items.Clear();
        String loc = Request.QueryString["return"];
        if (loc == null) SetInitialView();
        else if (loc[0] == 'a') Response.Redirect("~/Advisor/Advisee.aspx?id=" + loc.Substring(1));
        else if (loc[0] == 't') Response.Redirect("~/Advisor/Template.aspx?view=editTemplate&id=" + loc.Substring(1));

    }
    //No delete button
    protected void DeleteButton_Click(object sender, EventArgs e)
    {
        if (CourseList.SelectedItem == null)
            return;
        if (StoredProcedures.deleteCourse(CourseList.SelectedItem.Value) == 0)
        {
            MessageBox.Show("There was a problem with deleting the course");
        }
        CourseList.Items.Remove(CourseList.SelectedItem);
        CourseList.ClearSelection();
    }
    //Not used
    protected void AddPreReq_Click(object sender, EventArgs e)
    {
        if (PrereqChoiceList.SelectedItem == null)
            return;
        PrereqList.Items.Add(PrereqChoiceList.SelectedItem);
        PrereqList.ClearSelection();
        PrereqChoiceList.Items.Remove(PrereqChoiceList.SelectedItem);
        PrereqChoiceList.ClearSelection();
    }
    //Not used
    protected void AddCoReq_Click(object sender, EventArgs e)
    {
        if (CoreqChoiceList.SelectedItem == null)
            return;
        CoreqList.Items.Add(CoreqChoiceList.SelectedItem);
        CoreqList.ClearSelection();
        CoreqChoiceList.Items.Remove(CoreqChoiceList.SelectedItem);
        CoreqChoiceList.ClearSelection();

    }
    protected void AddTag_Click(object sender, EventArgs e)
    {
        if (TagChoiceList.SelectedItem == null)
            return;
        TagList.Items.Add(TagChoiceList.SelectedItem);
        TagList.ClearSelection();
        TagChoiceList.Items.Remove(TagChoiceList.SelectedItem);
        TagChoiceList.ClearSelection();
    }
    protected void RemovePreReq_Click(object sender, EventArgs e)
    {
        if (PrereqList.SelectedItem == null)
            return;
        PrereqChoiceList.Items.Add(PrereqList.SelectedItem);
        PrereqList.Items.Remove(PrereqList.SelectedItem);
        PrereqChoiceList.ClearSelection();
        PrereqList.ClearSelection();
    }
    protected void RemoveCoReq_Click(object sender, EventArgs e)
    {
        if (CoreqList.SelectedItem == null)
            return;
        CoreqChoiceList.Items.Add(CoreqList.SelectedItem);
        CoreqList.Items.Remove(CoreqList.SelectedItem);
        CoreqChoiceList.ClearSelection();
        CoreqList.ClearSelection();
    }
    protected void RemoveTag_Click(object sender, EventArgs e)
    {
        if (TagList.SelectedItem == null)
            return;
        TagChoiceList.Items.Add(TagList.SelectedItem);
        TagList.Items.Remove(TagList.SelectedItem);
        TagChoiceList.ClearSelection();
        TagList.ClearSelection();
    }
    protected void ManageButton_Click(object sender, EventArgs e)
    {
        if (CourseList.SelectedIndex == -1)
        {
            return;
        }
        ManageGivenCourse(CourseList.SelectedItem.Value);
    }

    /// <summary>
    /// fillCourseAttributes
    /// 
    /// Sets preReq and coReq logic for display
    /// </summary>
    private void fillCourseAttributes()
    {
        // Table of all course prerequisites
        List<Dictionary<String, Object>> results = StoredProcedures.getCoursePrerequisites(CourseID.Text);
        // Sets of prereqs for logic reasons
        String lastSet = "";
        String lastSubset = "";
        //AND and OR list items
        ListItem addAND = new ListItem("---------AND---------");
        ListItem addOR = new ListItem("----OR----");
        //only sets these elements if there are pre reqs to record
        if (results.Count() > 0)
        {
            lastSet = results.ElementAt(0)["preReqSet"].ToString();
            lastSubset = results.ElementAt(0)["preReqSubset"].ToString();
        }
        foreach(Dictionary<String, Object> i in results)
        {
            //Set and subset of the next element on the list
            String set = i["preReqSet"].ToString();
            String subset = i["preReqSubset"].ToString();
            //ListItems to add
            ListItem newItem = new ListItem("");
            //MessageBox.Show("HERE: "+i["preReqHigh"].GetType());
            if(i["preReqHigh"]==System.DBNull.Value)
                newItem = new ListItem("" + i["dpt"] + i["preReqLow"]);
            else
                newItem = new ListItem("" + i["dpt"] + i["preReqLow"] + " to " + i["dpt"] + i["preReqHigh"]);

            if (set != null && set != lastSet)
            {
                if (PrereqList.Items.Count > 0)
                {
                    PrereqList.Items.Add("\n");
                    PrereqList.Items.Add(addAND);//CHANGE
                    PrereqList.Items.Add("\n");
                }
                // new subset
                if (subset != null && subset != lastSubset)
                {
                    PrereqList.Items.Add(newItem);   
                    lastSubset = subset;
                }
                // existing subset
                else if (subset != null && subset == lastSubset)
                {
                    PrereqList.Items.Add(newItem);  
                }
                // no subset
                else // subset == null
                {
                    if (PrereqList.Items.Count > 0 && subset != lastSubset)
                    {
                        PrereqList.Items.Add(addOR);
                    }

                    PrereqList.Items.Add(newItem);  
                    
                    lastSubset = subset;
                }
                //set lastSet to this set
                lastSet = set;
                //lastSubset = "";
            }
            else if (set != null && set == lastSet)
            {
                // new subset
                if (subset != null && subset != lastSubset)
                {
                    if (PrereqList.Items.Count > 0)
                    {
                        PrereqList.Items.Add(addOR);
                    }

                    PrereqList.Items.Add(newItem);  

                    lastSubset = subset;
                }
                // existing subset
                else if (subset != null && subset == lastSubset)
                {
                    PrereqList.Items.Add(newItem);  
                }
                // no subset
                else // subset == null
                {
                    if (PrereqList.Items.Count > 0 && subset != lastSubset)
                    {
                        PrereqList.Items.Add(addOR);
                    }

                    PrereqList.Items.Add(newItem);  
                    lastSubset = subset;
                }
            }
            else // set is null
            {
                if (PrereqList.Items.Count > 0 && set != lastSet)
                {
                    PrereqList.Items.Add("\n");
                    PrereqList.Items.Add(addAND);//CHANGE
                    PrereqList.Items.Add("\n");
                }
            }
            //PrereqChoiceList.Items.Remove(newItem);
        }
        //fill coreqs
        results = StoredProcedures.getCourseCoreqs(CourseID.Text);
        foreach (Dictionary<String, Object> i in results)
        {
            ListItem newItem = new ListItem("" + i["dpt"] + " " + i["num"] + ": " + i["name"] + ", Credits: " + i["credits"], "" + i["courseID"]);
            CoreqList.Items.Add(newItem);
            CoreqChoiceList.Items.Remove(newItem);
        }
        //fill tags
        results = StoredProcedures.getCourseTags(CourseID.Text);
        foreach (Dictionary<String, Object> i in results)
        {
            String displayedSemester = "BLAHBLAH";
            int tag = Convert.ToInt32(i["tag"]);
            if(tag == 1)
                displayedSemester = "Fall";
            else if(tag == 2)
                displayedSemester = "Spring";
            else if(tag == 3)
                displayedSemester = "Summer";
            ListItem newItem = new ListItem(displayedSemester, tag + "");
            TagList.Items.Add(newItem);
            TagChoiceList.Items.Remove(newItem);
        }
    }

    protected void FindButton_Click(object sender, EventArgs e)
    {
        if (SubjectList.SelectedIndex == -1)
        {
            SubjectList.SelectedIndex = 0;
        }
        CourseHeader.Text = SubjectList.SelectedItem.Text;
        List<Dictionary<String, Object>> results;
        if (SubjectList.SelectedIndex == 0)
        {
            results = StoredProcedures.getListOfCourses();
        }
        else
        {
            results = StoredProcedures.getListOfCoursesFiltered(SubjectList.SelectedItem.Value);
        }
        CourseList.Items.Clear();
        foreach (Dictionary<String, Object> i in results)
        {
            CourseList.Items.Add(new ListItem("" + i["dpt"] + " " + i["num"] + ": " + i["name"] + ", Credits: " + i["credits"], "" + i["courseID"]));
        }
    }
    private void ManageGivenCourse(String cid)
    {
        HeaderText.Text = "Manage Course";
        ManageTable0.Visible = false;
        ManageTable0.Enabled = false;
        ManageTable1.Visible = false;
        ManageTable1.Enabled = false;
        ManageTable2.Visible = false;
        ManageTable2.Enabled = false;
        ManageTable3.Visible = true;
        ManageTable3.Enabled = true;
        SaveCourseButton.Visible = true;
        SaveCourseButton.Enabled = true;
        CancelButton.Visible = true;
        CancelButton.Enabled = true;
        Dictionary<String, Object> result = StoredProcedures.getCourse(cid);
        if (result != null)
        {
            SubjectName.Text = result["dpt"].ToString();
            CourseNumber.Text = result["num"].ToString();
            CourseTitle.Text = result["name"].ToString();
            CourseID.Text = result["courseID"].ToString();
        }
        List<Dictionary<String, Object>> results = StoredProcedures.getListOfCourses();
        PrereqChoiceList.Items.Clear();
        CoreqChoiceList.Items.Clear();
        
        foreach (Dictionary<String, Object> i in results)
        {
            PrereqChoiceList.Items.Add(new ListItem("" + i["dpt"] + " " + i["num"] + ": " + i["name"] + ", Credits: " + i["credits"], "" + i["courseID"]));
            CoreqChoiceList.Items.Add(new ListItem("" + i["dpt"] + " " + i["num"] + ": " + i["name"] + ", Credits: " + i["credits"], "" + i["courseID"]));
        }
        TagChoiceList.Items.Clear();
        TagChoiceList.Items.Add(new ListItem("Fall", "1"));
        TagChoiceList.Items.Add(new ListItem("Spring", "2"));
        TagChoiceList.Items.Add(new ListItem("Summer", "3"));

        SemesterList.Items.Clear();
        SemesterList.Items.Add(new ListItem("Fall", "1"));
        SemesterList.Items.Add(new ListItem("Spring", "2"));
        SemesterList.Items.Add(new ListItem("Summer", "3"));
        //Get the current date and predict enrollment 3 years backwards and forwards
        DateTime now = DateTime.Now;
        int currYear = now.Year;
        YearList.Items.Clear();
        for (int z = -3; z < 4; z++)
        {
            YearList.Items.Add(new ListItem((currYear + z).ToString() ));
        }
        

        //Additions for enrollment prediction
        EnrollmentPredictionLabel.Text = "Predicted Enrollment: ";
       

        fillCourseAttributes();
    }

    //handle the clicking of the course enrollment search button
    protected void MagicBall_Click(object sender, EventArgs e)
    {
        String term = SharedFunctions.convertToTermCode(YearList.SelectedItem.Text, SemesterList.SelectedItem.Text);
        Dictionary<String, Object> numCourse = StoredProcedures.getCoursePrediction(CourseID.Text, term);
        Dictionary<String, Object> numElective = StoredProcedures.getElectivePrediction(CourseID.Text, term);
        PredictedEnrollment.Text = ((int)numCourse["count"] + (int)numElective["count"]).ToString();
       
    }

    private void SetInitialView()
    {
        HeaderText.Text = "Manage Courses";
        ManageTable0.Visible = true;
        ManageTable0.Enabled = true;
        ManageTable1.Visible = true;
        ManageTable1.Enabled = true;
        ManageTable2.Visible = true;
        ManageTable2.Enabled = true;
        ManageTable3.Visible = false;
        ManageTable3.Enabled = false;
        SaveCourseButton.Visible = false;
        SaveCourseButton.Enabled = false;
        CancelButton.Visible = false;
        CancelButton.Enabled = false;
    }
}